<?php

include '../includes/general.init.php';

if (!is_dir(ADM_TEM_DIR))
{
	gerror_page(
		'Template Error', 
		'The specfied template folder does not exist.'
	);
}

$tpl->setPath('template', ADM_TEM_DIR);

$tpl->heading = 'login';

if ($user->is_logged_in)
{
	
	if (isset($_GET['logout']))
	{
		$logout = session::delete($_SERVER['REMOTE_ADDR']);
		$user = new user($_SERVER['REMOTE_ADDR']);
		$tpl->user = $user->user_info;
		$tpl->is_logged_in = false;
		switch($logout)
		{
			case true:
				$tpl->message = 'Logged out successfully.';
			break;
			case false:
				$tpl->message = 'Could not log you out.';
			break;
		}
	}
	else
	{
		redirect('index.php');
	}
	
}
else
{
	
	if (!empty($_POST))
	{
		$recaptcha_resp = null;
		$recaptcha_error = null;
		$recaptcha_resp = recaptcha_check_answer (set::get('recaptcha_private_key'),
                                $_SERVER['REMOTE_ADDR'],
                                $_POST['recaptcha_challenge_field'],
                                $_POST['recaptcha_response_field']);

		if ($recaptcha_resp->is_valid)
		{
			$user_login = $user->login($_POST['user'], $_POST['pass'], $_SERVER['REMOTE_ADDR']);
			if ($user->is_logged_in == true)
			{
				redirect('index.php');
				$tpl->message = 'You have been logged in successfully. Please wait while you are being redirected.';
				$tpl->meta[] = gen_meta(3, 'index.php');
			}
			else
			{
				switch($user_login)
				{
					case 'session':
						$tpl->message = 'There has been an error with the script. It cannot create your session on the server.';
						
					break;
					case 'password':
						$tpl->message = 'You have entered an incorrect password.';
					break;
					case 'exist':
						$tpl->message = 'That user does not exist.';
					break;
				}
			}
		}
		else
		{
			$tpl->message = 'The reCaptcha you have entered was entered incorrectly. ' . br;
			$tpl->message .= 'reCaptcha said: ' . $recaptcha_resp->error . br . br;
		}
	}
}

$tpl->display('gen_header.php');
$tpl->display('page_login.php');
$tpl->display('gen_footer.php');

session::clear_old();